package Server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * 
 * 
 * @author Christopher Koller
 *
 */
public class mNewConnectionListener extends Thread {

	private mServer controller;
    private ServerSocket listener;
    private volatile boolean stopThread = false;

    public mNewConnectionListener(mServer controller, int port) throws IOException {
        super("Listener:" + port);
        this.controller = controller;
        listener = new ServerSocket(port);
    }

    /**
     * 
     * @author Christopher Koller
     *
     */
    public void stopListening() {
        if (!this.stopThread) {
            this.stopThread = true;
            try {
                listener.close();
            } catch (IOException e) {
                
            }
        }
    }

    /**
     * Lässt den Servern weiter auf Anfragen der Clients warten
     * 
     * @author Christopher Koller
     *
     */
    @Override
    public void run() {
        while (!stopThread) {
            Socket socket;
            try {
                socket = listener.accept(); // wait for a request
                mServerSessions newClient = new mServerSessions(controller, socket);
                controller.addClient(newClient); // process the request
                System.out.println("New Client Connected!");
            } catch (IOException e) {
                // TODO Add error handling
            }
        }
    }


}
